/**
 * @description 整体特征
 * @author gf
 */
import { PageWrapper } from "@/components/PageWrapper";
import { Title } from "@/components/Title";
import LittleTitle from "@/components/Title/littleTitle";
import { RenderDesc } from "../FixedAssets";
import styled from "styled-components";
import styles from "./index.less";
import styles2 from "../FixedAssets/index.less";
import * as _ from "lodash";

import {
  getPortfolioFundTypeAllocation,
  getPortfolioAssetTypeAllocation,
  queryFieldTree, // 查询动态表头树
  queryList, // 当前组合整体持仓查询列表
} from "./service";
import { queryPortFolioEvent } from "../StockFixedAssets/fixedAssets";
import { useEffect, useState } from "react";
import { getUrlParam } from "@/utils/utils";
import Area, { DataProps } from "@/components/EchartsComponents/Area";
import { getBaseColors } from "@/utils/echarts";
import WarningTitle from "@/components/Title/WarningTitle";
import { FlexDiv } from "@/components/FOF/SelectInput";
import icon_expend from "@/assets/icons/icon-arrow.png";
import icon_setting from "@/assets/icons/icon-set.png";
import { Table, Button, Popover } from "antd";
import { queryPortfolioEventList } from "../PortfolioOverview/portfolio";
import dayjs from 'dayjs';
import EventEmpty from "@/components/FOF/EventEmpty";
import cn from "classnames";
import ColumnSelector, {
  _generalTreeData,
} from "@/components/ColumnSelectorFilter";

export const EBox = styled.div`
  position: relative;
  width: 100%;
  min-width: 800px;
  /* min-height: 230px; */
  border: 1px solid #e4e4e4;
  border-radius: 2px;
  margin-top: 4px;
`;
const GreyBgc = styled.div`
  background: #eff2f7;
  /* height: 134px; */
  border-radius: 0 0 2px 2px;
  margin: 0 -1px;
  border-left: 1px solid #e4e4e4;
  border-right: 1px solid #e4e4e4;
  padding: 8px;
`;

const WhiteBgc = styled.div`
  background: #fff;
  /* height: 118px; */
  padding: 8px;
`;

export const FlexBetweenDiv = styled(FlexDiv)`
  justify-content: space-between;
  align-items: flex-start;
  > img {
    position: relative;
    top: 3px;
    width: 16px;
    height: 16px;
    &:hover {
      cursor: pointer;
    }
  }
`;

const id = getUrlParam("id");
const time = getUrlParam("time");
const columnsFixed: any = [
  {
    title: () => (
      <div className={styles.table_title}>
        <p>序号</p>
        <p></p>
      </div>
    ),
    dataIndex: "order",
    key: "order",
    width: 50,
    render: (text, records, index) => (
      <span
        style={{
          textAlign: "center",
          display: "inline-block",
          width: "100%",
        }}
      >
        {index + 1}
      </span>
    ),
    fixed: "left",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>基金代码</p>
        <p></p>
      </div>
    ),
    dataIndex: "secuCode",
    key: "secuCode",
    width: 100,
    ellipsis: true,
    render: (text) => text || "-",
    fixed: "left",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>基金简称</p>
        <p></p>
      </div>
    ),
    dataIndex: "secuAbbr",
    key: "secuAbbr",
    width: 100,
    ellipsis: true,
    render: (text) => text || "-",
    fixed: "left",
  },
];
const handleNumber = (text) => {
  return text || text === 0 ? text : "-";
};

const specialRender = (text) => {
  return (
    <>
      <span className={styles.left} title={handleNumber(text?.profit)}>
        {handleNumber(text?.profit)}
      </span>
      <span
        className={styles.right}
        title={`(${handleNumber(text?.rank)}/${handleNumber(text?.count)})`}
      >
        <em> (</em>
        <em>
          {handleNumber(text?.rank)}/{handleNumber(text?.count)})
        </em>
      </span>
    </>
  );
};
const detailColumnsConvert: any = [
  {
    title: () => (
      <div className={styles.table_title}>
        <p>基金经理</p>
        <p></p>
      </div>
    ),
    dataIndex: "fundManagerName",
    key: "fundManagerName",
    width: 100,
    ellipsis: true,
    render: (text) => text || "-",
    fixed: "left",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>成立时间</p>
        <p></p>
      </div>
    ),
    dataIndex: "establishDate",
    key: "establishDate",
    width: 100,
    ellipsis: true,
    render: (text) => text || "-",
    fixed: "left",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>最新规模</p>
        <p>(亿)</p>
      </div>
    ),
    dataIndex: "fundScale",
    key: "fundScale",
    width: 65,
    ellipsis: true,
    render: (text) => handleNumber(text),
    fixed: "left",
    align: "right",
  },

  {
    title: () => (
      <div className={styles.table_title}>
        <p>持仓比例</p>
        <p>(%)</p>
      </div>
    ),
    dataIndex: "ratioInTotalAsset",
    key: "ratioInTotalAsset",
    width: 65,
    ellipsis: true,
    render: (text) => handleNumber(text),
    fixed: "left",
    align: "right",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>WInd一级分类</p>
        <p></p>
      </div>
    ),
    dataIndex: "firstFTypeName",
    key: "firstFTypeName",
    width: 122,
    render: (text) => text || "-",
    ellipsis: true,
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>WInd二级分类</p>
        <p></p>
      </div>
    ),
    dataIndex: "secFTypeName",
    key: "secFTypeName",
    width: 122,
    render: (text) => text || "-",
    ellipsis: true,
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>WInd三级分类</p>
        <p></p>
      </div>
    ),
    dataIndex: "thirdFTypeName",
    key: "thirdFTypeName",
    width: 122,
    render: (text) => text || "-",
    ellipsis: true,
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>近一月收益</p>
        <p>(同类排名)(%)</p>
      </div>
    ),
    dataIndex: "profitOneMonth",
    key: "profitOneMonth",
    width: 148,
    render: (text, record: any, index: number) => specialRender(text),
    // ellipsis: true,
    align: "center",
    // className:styles.special_td,
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>近三月收益</p>
        <p>(同类排名)(%)</p>
      </div>
    ),
    dataIndex: "profitThreeMonth",
    key: "profitThreeMonth",
    width: 148,
    render: (text, record: any) => specialRender(text),
    ellipsis: true,
    align: "center",
    // className:styles.special_td,
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>近六月收益 </p>
        <p>(同类排名)(%)</p>
      </div>
    ),
    dataIndex: "profitSixMonth",
    key: "profitSixMonth",
    width: 148,
    ellipsis: true,
    render: (text, record: any, index: number) => specialRender(text),
    align: "center",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>近一年收益 </p>
        <p>(同类排名)(%)</p>
      </div>
    ),
    dataIndex: "profitOneYear",
    key: "profitOneYear",
    width: 148,
    render: (text, record: any) => specialRender(text),
    ellipsis: true,
    align: "center",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>近三年收益</p>
        <p>(同类排名)(%)</p>
      </div>
    ),
    dataIndex: "profitThreeYear",
    key: "profitThreeYear",
    width: 148,
    render: (text, record: any) => specialRender(text),
    ellipsis: true,
    align: "center",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>成立以来收益</p>
        <p>(%)</p>
      </div>
    ),
    dataIndex: "profitSinceEstablishment",
    key: "profitSinceEstablishment",
    // width: 105,
    width: 148,
    render: (text, record: any, index: number) => handleNumber(text?.profit),
    ellipsis: true,
    // className: styles.special_td,
    align: "right",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>买入后收益</p>
        <p>(%)</p>
      </div>
    ),
    dataIndex: "fluctuationRange",
    key: "fluctuationRange",
    width: 84,
    ellipsis: true,
    render: (text) => handleNumber(text),
    align: "right",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>近一月最大回撤</p>
        <p>(%)</p>
      </div>
    ),
    dataIndex: "maxDrawdownOneMonth",
    key: "maxDrawdownOneMonth",
    width: 106,
    ellipsis: true,
    render: (text) => handleNumber(text),
    align: "right",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>近三月最大回撤</p>
        <p>(%)</p>
      </div>
    ),
    dataIndex: "maxDrawdownThreeMonth",
    key: "maxDrawdownThreeMonth",
    width: 106,
    ellipsis: true,
    render: (text) => handleNumber(text),
    align: "right",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>近六月最大回撤</p>
        <p>(%)</p>
      </div>
    ),
    dataIndex: "maxDrawdownSixMonth",
    key: "maxDrawdownSixMonth",
    width: 106,
    ellipsis: true,
    render: (text) => handleNumber(text),
    align: "right",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>近一年最大回撤</p>
        <p>(%)</p>
      </div>
    ),
    dataIndex: "maxDrawdownOneYear",
    key: "maxDrawdownOneYear",
    width: 106,
    ellipsis: true,
    render: (text) => handleNumber(text),
    align: "right",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>近三年最大回撤</p>
        <p>(%)</p>
      </div>
    ),
    dataIndex: "maxDrawdownThreeYear",
    key: "maxDrawdownThreeYear",
    width: 106,
    ellipsis: true,
    render: (text) => handleNumber(text),
    align: "right",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>成立以来最大回撤</p>
        <p>(%)</p>
      </div>
    ),
    dataIndex: "maxDrawdownSinceEstablishment",
    key: "maxDrawdownSinceEstablishment",
    width: 115,
    ellipsis: true,
    render: (text) => handleNumber(text),
    align: "right",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>收益贡献</p>
        <p>(调仓以来)(%)</p>
      </div>
    ),
    dataIndex: "revenueContribution",
    key: "revenueContribution",
    width: 80,
    ellipsis: true,
    render: (text) => handleNumber(text),
    align: "right",
  },
  {
    title: () => (
      <div className={styles.table_title}>
        <p>风险贡献</p>
        <p>(调仓以来)(%)</p>
      </div>
    ),
    dataIndex: "riskContribution",
    key: "riskContribution",
    width: 80,
    ellipsis: true,
    render: (text) => handleNumber(text),
    align: "right",
  },
];

const OverAllFeature = () => {
  type Chart = {
    xaxis: string[]; // x轴为字符串数组
    legend: string[];
    yaxis: DataProps[];
  };
  type ResponsePort = {
    [key: string]: any;
  };
  const [fundChart, setFundChart] = useState<Chart>();
  const [assetChart, setAssetChart] = useState<Chart>();
  const [expended, setExpended] = useState<boolean>(false);
  const [bTable, setBTable] = useState([]);
  const [eventInfo, setEventInfo] = useState({
    dataMessage: "",
    eventHeader: "",
    eventDate: "",
  });

  const [columnSetVisible, setColumnSetVisible] = useState(false); // 列选择器
  const [checkedKeys, setCheckedKeys] = useState([]); // 列选择器
  const [checkedIds, setCheckedIds] = useState([]); // 列选择器
  const [checkedKeys2, setCheckedKeys2] = useState([]); // 列选择器
  const [checkedIds2, setCheckedIds2] = useState([]); // 列选择器

  const [searchTableFieldDTOList, setSearchTableFieldDTOList] = useState([]); //树选择结构

  const [tableList, setTableList] = useState([]); //当前组合整体持仓
  const [columns, setColumns] = useState([]);

  const [treeResult, setTreeResult] = useState({});

  const [loading, setLoading] = useState(true);

  // 改变自定义列
  const changeColumns = (arr: any[]) => {
    console.log("checkedIds2", checkedIds2, "checkedKeys2", checkedKeys2);
    // debugger
    setCheckedIds(checkedIds2);
    setCheckedKeys(checkedKeys2);
    getListByIds(checkedIds2);
    setColumnSetVisible(false);
    // 可以将变动传出来本地改，在这之前默认的列需要保存下来
    // console.log(arr, columns);

    // // 最直接的是调接口查询
    // handleQueryShowColumns()
    // changePage({ current, pageSize: sortInfo?.pageSize, keyName: sortInfo?.keyName, isAsc: sortInfo?.isAsc })
  };

  useEffect(() => {
    getPortfolioAssetTypeAllocation({
      portfolioCode: id,
    }).then((res: ResponsePort) => {
      if (res?.code === "0") {
        setAssetChart(res?.data);
      }
    });

    getPortfolioFundTypeAllocation({
      portfolioCode: id,
    }).then((res: ResponsePort) => {
      if (res?.code === "0") {
        setFundChart(res?.data);
      }
    });
    queryPortFolioEvent({
      eventCode: "portfolio_asset_allocation_alert",
      portFolioCode: id,
    }).then((res) => {
      if (res?.code === "0") {
        const data =
          res?.data?.portfolioAssetAllocationAlertVO
            ?.portfolioAssetAllocationAlertList || [];
        setBTable(data);
        const dom = document.getElementById("overview-feature");
        if (dom && time) {
          setTimeout(() => {
            dom.scrollTop = 1000;
          }, 50);
        }
      }
    });
    queryPortfolioEventList({
      eventCodes: ["portfolio_asset_allocation_alert"],
      portfolioCode: id,
    }).then((res) => {
      if (res.code === "0" && res.data?.length > 0) {
        setEventInfo(res.data[0]);
      } else {
        // setEventList([]);
      }
    });

    queryFieldTree().then((res) => {
      if (res?.code === "0" && res?.data?.searchTableFieldDTOList?.length > 0) {
        const newList = res?.data?.searchTableFieldDTOList.map((item) =>
          item ? { ...item, checked: true } : {}
        );
        setSearchTableFieldDTOList(newList);
        const checks: string[] = [];
        const checksIds = [];
        const checksCols = [];
        const result = _generalTreeData(newList, checks, checksIds, checksCols);
        // debugger
        setTreeResult(result);
        getListByIds(result?.checksIds); //请求列表
        setCheckedKeys2(result?.checks); //展示用
        setCheckedKeys(result?.checks); //请求用
        setCheckedIds2(result?.checksIds); //展示用
        setCheckedIds(result?.checksIds); //请求用
        setColumns([
          ...columnsFixed,
          ...detailColumnsConvert.filter((item) => {
            return result?.checksCols.includes(item.key);
          }),
        ]);
      } else {
        setSearchTableFieldDTOList([]);
      }
    });
    // queryList({
    //   eventCodes: ["portfolio_asset_allocation_alert"],
    //   portfolioCode: id,
    // }).then((res) => {
    //   if (res.code === "0" && res.data?.length > 0) {
    //     setEventInfo(res.data[0]);
    //   } else {
    //     // setEventList([]);
    //   }
    // });
  }, [id]);

  useEffect(() => {
    if (time) {
      setExpended(true);
    }
  }, [time]);

  const changeCheckedKeys = (checkedArr: any) => {
    console.log("changeCheckedKeys", checkedArr);
    setCheckedKeys2(checkedArr); //展示用
    // setCheckedKeys(checkedArr)
  };

  const getListByIds = (checkedArr: any) => {
    console.log("getListByIds", checkedArr);
    setLoading(true);
    queryList({
      portfolioCode: id,
      ids: checkedArr.filter((item) => item || item === 0),
    }).then((res) => {
      if (
        res?.code === "0" &&
        res?.data?.portfolioOverallPositionList?.length > 0
      ) {
        setTableList([...res?.data?.portfolioOverallPositionList]);
        // setTableList([...res?.data?.portfolioOverallPositionList,...res?.data?.portfolioOverallPositionList,...res?.data?.portfolioOverallPositionList]);
        const fieldCodeList =
          res?.data?.fieldCodeList?.length > 0 ? res?.data?.fieldCodeList : [];
        setColumns([
          ...columnsFixed,
          ...detailColumnsConvert.filter((item) => {
            console.log(
              "2222-item",
              item,
              "item.key",
              item.key,
              "fieldCodeList",
              fieldCodeList,
              res
            );
            return fieldCodeList.includes(item.key);
          }),
        ]);
      } else {
        setTableList([]);
        setColumns([...columnsFixed, ...detailColumnsConvert]);
      }
      setLoading(false);
      console.log("queryList", res);
    });
  };
  const changeCheckedIds = (checkedArr: any) => {
    setCheckedIds2(checkedArr); //请求用
  };

  return (
    <PageWrapper narrow minWidth="1068px" id="overview-feature">
      <Title style={{ marginLeft: 16, marginBottom: 12 }}>组合整体特征</Title>
      <RenderDesc />
      <div className={cn(styles2.holderDetail, styles2.mt12)}>
        <div className={styles.head_container}>
          <div className={styles.head_title}>
            <LittleTitle title="当前组合整体持仓" mt="0px" />
            {/* <span className={styles.title_remark}>（板块配置比例统计的是单一板块比例占股票总资产的比例。板块采用自定义分类。）</span> */}
          </div>
          <Popover
            content={
              <ColumnSelector
                title="指标自定义"
                columnOptions={[]}
                // checkedValues={[]}
                treeResult={treeResult}
                checkedKeys={checkedKeys2}
                changeColumns={changeColumns}
                changeCheckedIds={changeCheckedIds}
                changeCheckedKeys={changeCheckedKeys}
                setPopoverVisible={setColumnSetVisible}
                style={{ height: "108px" }}
                visible={columnSetVisible}
                tableId={1}
                searchTableFieldDTOList={searchTableFieldDTOList}
              ></ColumnSelector>
            }
            visible={columnSetVisible}
            placement="left"
            onVisibleChange={(visible) => {
              visible && setColumnSetVisible(visible);
            }}
            overlayClassName={[styles.popoverStyle, styles.bond].join(" ")}
            overlayInnerStyle={{ width: 312, borderRadius: 2 }}
            destroyTooltipOnHide={true}
            arrowPointAtCenter={true}
            trigger="click"
          >
            <Button
              className={styles.setting_button}
              icon={
                <img
                  style={{ opacity: "0.7" }}
                  className="findfit_icon"
                  src={icon_setting}
                />
              }
              onClick={() => {}}
            />
          </Popover>
        </div>

        <div className={cn(styles2.holderDetail_table, styles.table_container)}>
          <Table
            className={cn(
              "list_table list_table_with_border table_header_center",
              styles2.cusFixTable,
              tableList?.length > 20 ? styles2.scrollTableConvertible : "",
              tableList?.length > 20 ? styles.scrollTableConvertible : ""
            )}
            columns={columns}
            dataSource={tableList}
            rowKey={(r) => r.bondInnerCode}
            pagination={false}
            style={{ whiteSpace: "nowrap" }}
            scroll={
              tableList?.length > 20
                ? {
                    y: 562,
                    x:
                      columns?.length > 0
                        ? columns.reduce(
                            (a, b) => (a?.width || 0) + (b?.width || 0)
                          )
                        : true,
                  }
                : {
                    x:
                      columns?.length > 0
                        ? columns.reduce(
                            (a, b) => (a?.width || 0) + (b?.width || 0)
                          )
                        : true,
                  }
            }
            loading={loading}
          />
        </div>
      </div>
      <LittleTitle title="各基金类型占市值的比例" />

      <EBox>
        {fundChart?.xaxis?.length > 0 ? (
          <div style={{ height: 230 }}>
            <Area
              idName="fund-area"
              xAxis={fundChart?.xaxis}
              data={fundChart?.yaxis || []}
              legend={
                fundChart?.yaxis ? fundChart.yaxis.map((v) => v.label) : []
              }
              color={getBaseColors()}
              percent={true}
              legendStyle={{ top: 5 }}
            />
          </div>
        ) : (
          <EventEmpty title="暂无数据" />
        )}
      </EBox>
      <LittleTitle title="各资产类型占市值的比例" />
      <EBox>
        {assetChart?.xaxis?.length > 0 ? (
          <div style={{ height: 230 }}>
            <Area
              idName="asset-area"
              xAxis={assetChart?.xaxis}
              data={assetChart?.yaxis || []}
              legend={
                assetChart?.yaxis ? assetChart.yaxis.map((v) => v.label) : []
              }
              color={getBaseColors()}
              showLine={true}
              percent={true}
              legendStyle={{ top: 5 }}
            />
          </div>
        ) : (
          <EventEmpty title="暂无数据" />
        )}
        {eventInfo.eventHeader && (
          <GreyBgc>
            <WhiteBgc>
              <FlexBetweenDiv
                onClick={() => {
                  setExpended((state) => !state);
                }}
                style={{ lineHeight: "20px" }}
              >
                <WarningTitle
                  title={`${
                    eventInfo.eventDate
                      ? dayjs(eventInfo.eventDate).format("YYYY/MM/DD")
                      : "-"
                  }  ${eventInfo.eventHeader}`}
                />
                <img
                  src={icon_expend}
                  style={{
                    transform: expended ? "rotate(0deg)" : "rotate(-90deg)",
                  }}
                  alt="arrow"
                />
              </FlexBetweenDiv>
              {expended && (
                <FlexBetweenDiv>
                  <div className={styles.bottom_text}>
                    {eventInfo.dataMessage && (
                      <div
                        className={styles.bottom_gray_text}
                        dangerouslySetInnerHTML={{
                          __html: eventInfo.dataMessage?.toLocaleString(),
                        }}
                      ></div>
                    )}
                    {/* <span className={styles.bottom_desc}>
                      *资产比例与阈值差异在5%以内。
                    </span> */}
                  </div>
                  <Table
                    className={styles.scrollTable}
                    columns={[
                      {
                        title: "资产类型",
                        dataIndex: "assetType",
                        key: "assetType",
                        width: 100,
                      },
                      {
                        title: "当前比重",
                        dataIndex: "assetAllocation",
                        key: "assetAllocation",
                        width: 200,
                        render: (text) => (
                          <span
                            style={{
                              display: "block",
                              paddingRight: `calc(50% - ${
                                bTable[0].assetAllocation.length * 3.5
                              }px)`,
                            }}
                          >
                            {text}
                          </span>
                        ),
                      },
                      {
                        title: "资产阈值",
                        dataIndex: "threshold",
                        key: "threshold",
                        width: 200,
                        render: (text) => (
                          <span
                            style={{
                              display: "block",
                              paddingRight: `calc(50% - ${
                                bTable[0].threshold.length * 3.5
                              }px)`,
                            }}
                          >
                            {text}
                          </span>
                        ),
                      },
                    ]}
                    dataSource={bTable}
                    rowKey={(r) => r.date}
                    rowClassName={(r, d) =>
                      r.flag === "1" ? styles.redRow : ""
                    }
                    bordered
                    pagination={false}
                  />
                </FlexBetweenDiv>
              )}
            </WhiteBgc>
          </GreyBgc>
        )}
      </EBox>
    </PageWrapper>
  );
};

export default OverAllFeature;
